/* enum */
import AuthEnum from '@model/enum/AuthEnum.ts'
import TaskStateEnum from '@model/enum/TaskStateEnum.ts'
import { TaskFieldNameMappingEnum } from '@model/enum/FieldMappingEnum.ts';
/* utils */
import { taskTypeSelectConversion } from '@src/util/conversionFunctionUtil.ts';
import _ from 'lodash';
import AuthUtil from '@src/util/auth'
import { getRootWindow } from '@src/util/dom';
import i18n from '@src/locales'
import {safeNewDate} from "@src/util/time";

export default {
  /** 
   * @description 是否允许新建客户
  */
  allowCreateCustomer() {
    return AuthUtil.hasAuth(this.auth, AuthEnum.CUSTOMER_CREATE)
  },
  // 是否有新建联系人权限
  allowCreateLinkman() {
    return AuthUtil.hasAuth(this.auth, AuthEnum.LINKMAN_ADD)
  },
  /** 
   * @description 是否允许编辑客户
  */
  allowEditCustomer() {
    return this.hasEditCustomerAuth
  },
  /** 
   * @description 是否允许新建产品
  */
  allowCreateProduct() {
    return AuthUtil.hasAuth(this.auth, AuthEnum.PRODUCT_CREATE)
  },
  /* 工单表单显示字段 过滤 产品关联字段 */
  taskFormFields() {
    return this.fields.filter(field => field.formType != 'relationProduct');
  },
  /* 客户字段 */
  customerField() {
    return this.fields.filter(f => f.fieldName === 'customer')[0];
  },
  customerFormDom() {
    return this?.customerFormView?.$refs?.CustomerCreateView || {};
  },
  /* 客户字段配置 */
  customerOption(){
    return (this.customerField.setting && this.customerField.setting.customerOption) || {} ;
  },
  /* 客户关联工单的数量数据 */
  customerRelevanceTaskCountData() {
    return this.relevanceTaskCountData[TaskFieldNameMappingEnum.Customer];
  },
  /* 是否效验计划时间 */
  isVilidatePlantime() {
    let { isTaskEdit, isPlanTaskEdit } = this.state || {}
    // 非编辑状态
    return !isPlanTaskEdit && !isTaskEdit
  },
  /** 
   * @description 是否显示 客户关联的工单数量 按钮 
   * 1. 客户存在
   * 2. 且 全部数量 大于 0
  */
  isShowCustomerRelevanceTaskCountButton() {
    let { all } = this.customerRelevanceTaskCountData;
    return (this.selectedCustomer?.id || this.selectedCustomer?.value) && Number(all) > 0;
  },
  /** 
   * @description 是否显示 产品关联的工单数量 按钮 
   * 1. 产品存在
   * 2. 且 全部数量 大于 0
   * 3. 且 当前选择的产品只有一个
  */
  isShowProductRelevanceTaskCountButton() {
    let { all } = this.productRelevanceTaskCountData;
    return (this.selectProduct?.id || this.selectProduct?.value) && Number(all) > 0 && this.value?.product?.length == 1;
  },
  /** 
   * @description 是否显示 同时通知客户 字段
   * 1. 新建工单/新建计划任务不显示
  */
  isShowNoticeCustomer() {
    let { isFromPlan, isTaskCreate } = this.state;
    return !isFromPlan && !isTaskCreate;
  },
  // 产品字段
  productField(){
    return {
      displayName: i18n.t('common.base.product'),
      fieldName: 'product',
      formType: 'select',
      isNull: this.customerOption?.productNotNull === true ? 0 : 1
    }
  },
  productFormDom() {
    return this?.productFormView?.$refs?.ProductCreateView || {};
  },
  /* 产品关联工单的数量数据 */
  productRelevanceTaskCountData() {
    return this.relevanceTaskCountData[TaskFieldNameMappingEnum.Product];
  },
  // 选择的客户值
  selectedCustomer(){
    return (this.value.customer && this.value.customer[0]) || {};
  },
  // 选择的产品值
  selectProduct() {
    return (this.value.product && this.value.product[0]) || {};
  },
  /* 工单类型 */
  taskTypes(){
    return this.types.map(type => taskTypeSelectConversion(type)) || [];
  },
  /* 工单类型对象 */
  taskTypesMap() {
    return _.reduce(this.taskTypes, (result, value) => {
      result[value.value] = value;
      return result;
    }, {})
  },
  /* 工单表单显示字段 过滤 产品关联字段 */
  taskFormFields() {
    return this.fields.filter(field => field.formType != TaskFieldNameMappingEnum.RelationProduct);
  },
  /* 产品关联字段 */
  relationProductfields() {
    return this.fields.filter(field => field.formType == TaskFieldNameMappingEnum.RelationProduct) 
    // 为隐藏和不可见的字段不显示
    .filter((field) => !field.isHidden && (field.isVisible == undefined || field.isVisible))
  },
  // /* 客户关联字段 */
  relationCustomerfields() {
    return this.fields.filter(field => field.formType == TaskFieldNameMappingEnum.RelationCustomer) 
    // 为隐藏和不可见的字段不显示
    .filter((field) => !field.isHidden && (field.isVisible == undefined || field.isVisible))
  },
  /** 当前登录的用户 */
  loginUser() {
    return this.initData.loginUser || {};
  },
  /**
   * 当前用户是否是该客户负责人
   * 客户负责人用于和客户创建人相同权限
   */
  isCustomerManager() {
    const customer = this.value.customer?.length ? this.value.customer[0] : {}
    const currentUser = this.loginUser
    return currentUser?.userId === customer?.customerManager
  },

  /**
   * 当前用户是否是该客户协同人
  */
   isCustomerSynergies() {
    const customer = this.value.customer?.length ? this.value.customer[0] : {}
    const currentUser = this.loginUser
    let customerSynergies = customer.synergies || []
    return !!customerSynergies.find(v => v.userId === currentUser?.userId)
  },

  /**
   * 当前用户是否是该客户负责人或协同人
   */
  isCustomerManagerOrSynergies() {
    return this.isCustomerManager || this.isCustomerSynergies
  },

  /**
   * 是否有编辑客户权限，需要满足以下条件之一：
   *
   * 1. 编辑客户全部权限： 全部客户
   * 2. 编辑客户团队权限： 没有团队的客户都可编辑，有团队的按团队匹配。 包含个人权限
   * 3. 编辑客户个人权限： 自己创建的 或 客户负责人
   */
  hasEditCustomerAuth() {
    const customer = this.value.customer?.length ? this.value.customer[0] : {}
    const loginUserId = this.loginUser.userId
    
    return AuthUtil.hasAuthWithDataLevel(
      this.auth,
      'CUSTOMER_EDIT',
      // 团队权限判断
      () => {
        let tags = Array.isArray(customer?.tags) ? customer.tags : []
        // 无团队则任何人都可编辑
        if (tags.length == 0) return true

        let loginUserTagIds = this.loginUser?.tagIdsWithChildTag || []
        return tags.some(tag => loginUserTagIds.indexOf(tag.id) >= 0)
      },
      // 个人权限判断
      () => {
        return customer?.createUser == loginUserId || this.isCustomerManagerOrSynergies
      }
    )
  },
  isShowSelect() {
    // 产品数据为空时，质保校验初始化。bugfix:17400
    if (!this.value.product || !this.value.product.length) {
      this.isQualityDialog = false
      this.isAllowQualityIn = false
      this.isFaultLibraryDialog = false
      this.noProductTypeId = false
      return true
    }

    if(this.isQualityDialog || this.isAllowQualityIn || this.isFaultLibraryDialog || this.noProductTypeId) {
      return false
    }
    return true
  },
  // 华大基因灰度
  isBgiSaas() {
    const RootWindow = getRootWindow(window)
    return Boolean(RootWindow.grayAuth?.bgiSaas)
  },
  /* 是否为 新建 || 编辑 || 复制计划任务页面 */
  isPlanTaskPage() {
    const path = window.location.pathname
    return (path.indexOf('/task/planTask/create') > -1) || (path.indexOf('/task/planTask/edit') > -1) || (path.indexOf('/task/planTask/copy') > -1);
  },
  qualityStartTime() {
    return this.value?.quality?.qualityStartTime
  },
  qualityEndTime() {
    return this.value?.quality?.qualityEndTime
  },
  qualityStatus() {
    return this.value?.quality?.qualityStatus
  },
  effectWikiFields() {
    return this.fields.filter(field => {
      return this.relationWikiSetting.includes(field.fieldName)
    }).filter(field => ['textarea', 'text'].includes(field.formType))
  },
  /* 故障库字段 */
  hasFaultLibraryField() {
    const hasFaultLibrary = this.fields.findIndex(field => field.fieldName == 'faultLibrary')
    return hasFaultLibrary > -1
  },
  faultLibraryField() {
    const faultLibrary = this.fields.filter(f => f.fieldName === 'faultLibrary')
    return faultLibrary ? faultLibrary[0] : {}
  },
  /* 故障库字段配置 */
  faultLibraryOption(){
    return (this.faultLibraryField?.setting && this.faultLibraryField.setting.faultLibraryOption) || {}
  },
  faultLibraryWikiId() {
    return this.value?.faultLibrary?.wikiId
  },
  // 是否允许添加未关联字段的产品
  isShowRelationCustomer() {
    const customerTemp = this.taskFormFields.find(item => item.formType === 'customer');
    return customerTemp?.setting?.showCustomerProduct || false;
  },
  // 后面有需求再放开
 /* planStartTimeDatePickerOptions() {
    return {
      disabledDate(time) {
        return time.getTime() < safeNewDate(safeNewDate().toLocaleDateString()).getTime()
      },
      selectableRange: this.getCurrentTimeRange('planStartTime')
    }
  },
  planEndTimeDatePickerOptions() {
    return {
      disabledDate(time) {
        return time.getTime() < safeNewDate(safeNewDate().toLocaleDateString()).getTime()
      },
      selectableRange: this.getCurrentTimeRange('planEndTime')
    }
  },*/
};